#include "core/file/Logger.h"
#include <QDateTime>
#include <QDebug>

Logger* Logger::instance(QObject *parent) {
    static Logger loggerInstance;
    return &loggerInstance;
}

Logger::Logger(QObject *parent) : QObject(parent), m_stream(&m_file)
{}

Logger::~Logger()
{
    if (m_file.isOpen())
        m_file.close();
}

void Logger::setLogFile(const QString &filePath)
{
    QMutexLocker locker(&m_mutex);

    if (m_file.isOpen())
        m_file.close();

    m_file.setFileName(qApp->applicationDirPath() + '/' + filePath.split('/').last().split('\\').last());
    if (!m_file.open(QIODevice::Append | QIODevice::Text))
    {
        qWarning() << "Unable to open log file:" << filePath;
    }
}

void Logger::log(const QString &message)
{
    QMutexLocker locker(&m_mutex);

    QString timeStampedMsg = QString("[%1] %2")
                                 .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"))
                                 .arg(message);

    if (m_file.isOpen())
    {
        m_stream << timeStampedMsg << "\n";
        m_stream.flush();
    }

    qDebug().noquote() << timeStampedMsg;
}
